<?php
namespace Home\Controller;
use Think\Controller;

class AdminController extends Controller{
	
	function index(){
		if(doAuth() != 10){
			echo "您没有访问权限！";
			return false;
		}
		
		if($_REQUEST['func']){
			$data	= $_REQUEST;
			$this->$data['func']($data);
		}else{
			$this->toDisplay();
		}
	}
	
	function changeValid($data){
		$newData	= array(
				"userid"	=> (int)$data['userid'],
				"valid"		=> 1-(int)$data['valid']
		);
		$status	= M("users")->where("userid = ".$newData['userid'])->data($newData)->save($newData);
		
		$this->toDisplay();
	}
	
	function addUser($data = null){
		if($data == null){
			$this->display("addUser");
		}else{
			$userData	= $_POST;
			$userData['nickname']	= substr($userData['username'],0,strrpos($userData['username'],"@"));
			$status	= D("Users")->toSignUp($userData,1);
			if($status == 10)
				$this->redirect("Home/Admin/index");
			else 
				$this->error($status);
		}
	}
	
	function userGroup($data = null){
		if($data != null){
			$groups	= M("auth_group")->select();
			$usergroups	= M("auth_group_access")->where("uid = ".(int)$data['userid'])->select();
		
			$ugs	= array();
			foreach($usergroups as $value){
				array_push($ugs,$value['group_id']);
			}
			foreach($groups as $key=>$value){
				if(in_array_case($value['id'], $ugs)){
					$groups[$key]['own'] = 1;
				}
			}
			
			$this->assign("userid", $data['userid']);
			$this->assign("userGroups", $groups);
			$this->display("userGroup");
		}else{
			$ugData	= array();
			foreach($_POST['ug'] as $value){
				array_push($ugData,array('uid'=>$_POST['userid'], 'group_id'=>$value));
			}
			$status	= M("auth_group_access")->where("uid = ".(int)$_POST['userid'])->delete();
			$status	= M("auth_group_access")->addAll($ugData);
			$this->toDisplay();
		}
	}
	
	function deleteUser($data = null){
		if($data != null){
			M("users")->where("userid = ".(int)$data['userid'])->delete();
			$this->toDisplay();
		}
	}
	
	function recoverPwd($data = null){
		if($data != null){
			$userData	= array(
					"userid"	=> $data['userid'],
					"password"	=> md5("12345678"),
			);
			M("users")->where("userid = ".(int)$data['userid'])->data($userData)->field("password")->save($userData);
			$this->toDisplay();
		}
	}
	
	function toDisplay(){
		$userlist	= M("users")->limit(0,10)->select();
		$this->assign("userlist", $userlist);
		$this->display('index');
	}
}